<template>
  <div class="page">
    <div class="title">
      <div class="icon">
        <img src="@/assets/logo.png" alt="">
      </div>
      <div class="name">Baby Baby Love</div>
    </div>
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="i in 3" :key="i">
        <div class="img">
          <img :style="{ borderRadius: '10px' }" :src="getImageUrl(i)" alt="">
        </div>
      </van-swipe-item>
      <template #indicator="{ active, total }">
        <div class="slide">
          <div class="custom-indicator" v-for="(item, index) in total" :class="(active + 1) == item ? 'active' : ''"
            :key="index"></div>
        </div>
      </template>
    </van-swipe>
    <!-- <van-button class="shouquan" block color="linear-gradient(90deg, #52A952, #40A5DB)">立即授权</van-button> -->
    <div class="zhiya">
      <div class="logo">
        <img src="@/assets/index.png" alt="">
      </div>
      <!-- <div class="item">
        <div class="leabel">实物资产编码</div>
        <div class="value">{{ proxy.plusXing('0x9b0B8487d5D283Ab1faffbC53fbe99479ed66d4f', 4, 6, '.', 4) }}</div>
      </div> -->
      <div class="item">
        <div class="leabel">NFT分红池地址</div>
        <div class="value" @click="proxy.copy(mainContractAddress)">{{ proxy.plusXing(mainContractAddress, 4, 6, '.', 4)
        }}</div>
      </div>
      <div class="item">
        <div class="leabel">参与起始时间</div>
        <div class="value">{{ dateNow.year }}/{{ dateNow.month }}/{{ dateNow.strDate }}</div>
      </div>
      <div class="item">
        <div class="leabel">终止时间</div>
        <div class="value">{{ queryDisTime(time.value) }}</div>
      </div>
      <div class="item">
        <div class="leabel">NFT余额</div>
        <div class="value">{{ BalanceNFT || 0 }}</div>
      </div>
      <div class="item">
        <div class="leabel">BBL余额</div>
        <div class="value">{{ BalanceFRM || 0 }}</div>
      </div>
      <div class="item">
        <div class="leabel">合约质押时长</div>
        <div class="value down" @click="showDown = true">
          <span>{{ time.name }}</span>
          <van-icon size="15" name="arrow-down" />
        </div>
      </div>
      <div class="item">
        <div class="leabel">质押类型</div>
        <div class="value down" @click="typeShow = true">
          <span>{{ typeNow.name }}</span>
          <van-icon size="15" name="arrow-down" />
        </div>
      </div>
      <div class="item">
        <div class="leabel">质押数量</div>
        <div class="value">
          <van-field v-model="PledgeNum" input-align="right" type="digit" label="" placeholder="请输入质押数量" />
        </div>
      </div>
      <van-button class="shouquan" block color="linear-gradient(90deg, #52A952, #40A5DB)" @click="participate"
        :disabled="PledgeNum ? false : true">参与质押</van-button>
    </div>
  </div>
  <van-popup v-model:show="show" closeable round>
    <div class="box">
      <div class="time">{{ year }}年</div>
      <div class="img">
        <img src="@/assets/tips.png" alt="">
      </div>
      <div class="tipsMain">
        <div>静态算力增加 {{ powerAdd }}</div>
        <div v-if="typeNow.name == 'BBL'">支付 {{ PledgeNum || 0 }} BBL</div>
        <div v-else>支付 {{ PledgeNum || 0 }} NFT</div>
      </div>
      <van-button class="shouquan" block color="linear-gradient(90deg, #52A952, #40A5DB)"
        :disabled="powerAdd ? false : true" :loading="powerAddLoading" @click="userAdd">确定参与</van-button>
    </div>
  </van-popup>
  <van-action-sheet close-on-click-action v-model:show="showDown" cancel-text="取消" :actions="actions"
    @select="onSelect" />
  <van-action-sheet close-on-click-action v-model:show="typeShow" cancel-text="取消" :actions="type"
    @select="onSelectType" />
  <Tabbar :active="1"></Tabbar>
</template>
<script setup name="index" lang="ts">
import Tabbar from '@@/Tabbar';
import {
  mainContractAddress
} from '@/utils/casinoContract'
import { ref, getCurrentInstance, onMounted, computed, watch } from 'vue'
import { isLoopInviter, addressSelf } from '@/api/request'
import contractStore from '@/store/modules/contract'
import { getNowFormatDate, queryDisTime } from '@/utils/filter.js'
import { Toast } from 'vant';
import * as BigToSmall from "@/utils/BNUtils.js";
import { useRouter } from "vue-router";

const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const show = ref(false)
const typeShow = ref(false)
const year = new Date().getFullYear()
const appStore = contractStore()
const dateNow = getNowFormatDate()
const BalanceFRM = computed(() => appStore.BalanceFRM)
const BalanceNFT = computed(() => appStore.BalanceNFT)
const empowerFRM = computed(() => appStore.empowerFRM)
const empowerNFT = computed(() => appStore.empowerNFT)
const contractInstance = computed(() => appStore.contractInstance)
const token = computed(() => appStore.token)
const nft = computed(() => appStore.nft)
const address = computed(() => appStore.address)
const nonce = computed(() => appStore.nonce)

const showDown = ref(false);
const powerAddLoading = ref(false)
const actions = ref([
  { name: '180天', value: 180 },
  { name: '360天', value: 360 },
  { name: '720天', value: 720 }
]);
const type = [
  { name: 'BBL', value: 'BBL' },
  { name: 'NFT', value: 'NFT' }
];
const power_ratio = {
  '180': 0.01,
  '360': 0.015,
  '720': 0.02
};
const typeNow = ref(type[0]);
const time = ref(actions.value[0])
const frm = ref(0)
const payNft = ref(0)
const PledgeNum = ref('')
const powerAdd = ref(0)
const parentAddress = ref('')
watch(nonce, (val) => {
  if (val != null) {
    proxy.userAuthorization(appStore, async (res: boolean) => {
      if (res) {
        await queryParent()
        let geturl = location.href
        if (geturl.indexOf('?') == -1) {
          return
        }
        let getqyinfo = geturl.split('?')[geturl.split('?').length - 1]
        let getqys = getqyinfo.split('&')
        let obj = {} as any  //创建空对象，接收截取的参数
        for (let i = 0; i < getqys.length; i++) {
          let item = getqys[i].split('=')
          let key = item[0]
          let value = item[1]
          obj[key] = value
        }
        let parms = obj.address
        console.log('parms', parms)
        if (parms) {
          await isLoopInviter(parms)
        }
      }
    })
  }
}, { immediate: true })

onMounted(() => {
  proxy.userAuthorization(appStore, (res: boolean) => {
    if (res) {
      queryParent()
    }
  })
})
const onSelect = (res: any) => {
  time.value = res
}
const queryParent = async() => {
  let ret = await addressSelf()
  if (ret.status == 200) {
    parentAddress.value = ret.data.parent
  }
}
const onSelectType = (res: any) => {
  typeNow.value = res
  if (res.name == 'NFT') {
    actions.value = [
      { name: '720天', value: 720 },
    ]
  } else {
    actions.value = [
      { name: '180天', value: 180 },
      { name: '360天', value: 360 },
      { name: '720天', value: 720 }
    ]
  }
  time.value = actions.value[0]
}
const participate = () => {
  //let ratio = power_ratio[time.value.value];
  if(parentAddress.value) {
    show.value = true
    powerAdd.value = typeNow.value.name == 'BBL' ? (+PledgeNum.value) * 0.01 : (+PledgeNum.value)
  } else {
    router.push({
      path: '/my',
      query: {
        isShow: 1
      }
    })
  }
}
const userAdd = async () => {
  let need = PledgeNum.value
  let needFrm = 0
  let needNft = 0
  if (typeNow.value.name == 'BBL') {
    needFrm = +need
  } else {
    needNft = +need
  }
  if (needFrm) {
    if (needFrm > BalanceFRM.value) {
      Toast('FRM余额不足')
      return
    }
    if (needFrm > empowerFRM.value) {
      powerAddLoading.value = true
      // 授权
      await userEmpower(needFrm, 'bbl', () => {
        //
        if (!needNft) {
          pledge()
        }
      })
    }
  }
  console.log("mainContractAddress", mainContractAddress);
  console.log('needNft', needNft, BalanceNFT.value, empowerNFT.value)
  if (needNft) {
    if (needNft > BalanceNFT.value) {
      Toast('NFT余额不足')
      return
    }
    if (!empowerNFT.value) {
      // 授权
      powerAddLoading.value = true
      await userEmpower(needNft, 'nft', () => {
        // 
        if (!needFrm) {
          pledge()
        }
      })
    }
  }
  console.log('empowerNFT.value', empowerNFT.value);
  console.log('needFrm', needFrm);
  if (empowerNFT.value && needFrm <= empowerFRM.value) {
    powerAddLoading.value = true
    pledge()
  }
}
// 授权
const userEmpower = async (mount: number, type: string, callback: any) => {
  let moun = BigToSmall.pow(mount, 18);
  let fn = '' as any
  try {
    if (type == 'bbl') {
      fn = token.value.methods
        .approve(mainContractAddress, moun)
    } else if (type == 'nft') {
      fn = nft.value.methods
        .setApprovalForAll(mainContractAddress, true)
    }
    fn.send({
      from: address.value,
    }).then((res: any) => {
      console.log('已授权', res)
      if (type == 'bbl') {
        appStore.SET_empowerFRM(mount)
      } else if (type == 'nft') {
        appStore.SET_empowerNFT(true)
      }
      callback()
    })
      .catch((err: any) => {
        console.log(err)
        powerAddLoading.value = false
      })
  } catch (error) {
    powerAddLoading.value = false
  }
}
// 质押
const pledge = async () => {
  console.log('质押')
  let moun = 0
  if (typeNow.value.name == 'BBL') {
    moun = BigToSmall.pow(PledgeNum.value, 18);
    payNft.value = 0
  } else {
    moun = 0
    payNft.value = +PledgeNum.value
  }
  console.log(moun, payNft.value, time.value.value)
  try {

    console.log("moun:", moun);
    console.log("payNft.value:", payNft.value);
    console.log("time.value.value:", time.value.value);
    console.log("address.value:", address.value);
    console.log('122133',await contractInstance.value.methods.frmTokenAddress().call());
    console.log('122133frmNftAddress',await contractInstance.value.methods.frmNftAddress().call());
    await contractInstance.value.methods.stake(moun, payNft.value, time.value.value).send({
      from: address.value
    })
    Toast('质押成功')
    PledgeNum.value = ''
    show.value = false
    changeBlc()
    powerAddLoading.value = false
  } catch (error) {
    Toast('质押失败')
    console.log("error:", error);
    powerAddLoading.value = false
  }
  powerAddLoading.value = false
}
const changeBlc = async () => {
  let usdts = await token.value.methods.balanceOf(address.value).call()
  let usdtRes = Number(BigToSmall.chufa(usdts, 18))
  appStore.SET_BalanceFrm(usdtRes)

  let gks = await nft.value.methods.balanceOf(address.value, 0).call()
  let gkRes = Number(gks)
  appStore.SET_BalanceNFT(gkRes)
}
const getImageUrl = (name: string|number) => {
  return new URL(`../../assets/${name}.jpg`, import.meta.url).href
}
</script>
<style scoped lang="less">
.slide {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;

  .custom-indicator {
    width: 22px;
    height: 7px;
    background: #CCCCCC;
    border-radius: 3px;
    margin-right: 5px;
  }

  .custom-indicator:last-child {
    margin-right: 0;
  }

  .active {
    background: #53B8E9;
  }
}

.box {
  display: flex;
  flex-direction: column;
  padding: 20px 24px;

  .tipsMain {
    margin-bottom: 13px;
    display: flex;
    flex-direction: column;
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #000000;
    line-height: 32px;
  }

  .img {
    width: 197px;
    height: 170px;
    margin: 25px 26px 18px 26px;
  }

  .time {
    font-size: 25px;
    font-family: PingFang SC;
    font-weight: 800;
    color: #000000;
  }
}

.page {
  background: #E9E9E9;
  min-height: calc(100vh - 50px);
  padding: 0 13px;

  .zhiya {
    margin-top: 15px;
    margin-bottom: 20px;
    background: #FFFFFF;
    border-radius: 15px;
    padding: 20px;

    .logo {
      width: 160px;
      // height: 48px;
      margin: auto;
      margin-bottom: 20px;
    }

    .item {
      line-height: 38px;
      display: flex;
      justify-content: space-between;

      .leabel {
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #767676;
        flex-shrink: 0;
      }

      .value {
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 800;
        color: #000000;

        :deep(.van-field) {
          padding: 0;
        }
      }

      .down {
        display: flex;
        align-items: center;
      }
    }
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 15px;
    padding-bottom: 15px;

    .icon {
      width: 48px;
      height: 48px;
      margin-right: 6px;
    }

    .name {
      font-size: 19px;
      font-family: PingFang SC;
      font-weight: 800;
      color: #000000;
    }
  }
}
</style>